import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import ElementUI from '../components/ElementUI.vue'
import Home from '../components/Home.vue'
import User from '../components/user/user.vue'
import ItemCat from '../components/items/ItemCat.vue'
import Item from '../components/items/Item.vue'
import AddItem from '../components/items/addItem.vue'

//使用路由机制
Vue.use(VueRouter)
const routes = [
  {path: '/', redirect: '/login'},
  {path: '/login', component: Login},
  {path: '/elementUI', component: ElementUI},
  {path: '/home', component: Home, children:[
    {path: '/user',component: User},
    {path: '/itemCat', component: ItemCat},
    {path: '/item', component: Item},
    {path: '/item/addItem', component: AddItem}
  ]},
  
]

//路由导航守卫!!!!!!!
const router = new VueRouter({
  routes
})

/**
 *  参数说明:
 *    1.to 到哪里去
 *    2.from 从哪里来
 *    3.next 请求放行
 *  拦截器策略:
 *    1.如果用户访问/login登录页面 直接放行
 *    2.如果访问其它页面,则校验是否有token
 *      有token     放行
 *      没有token   跳转到登录页面
 */
router.beforeEach((to,from,next) => {
  if(to.path === '/login') return next()
  //获取token数据信息
  let token = window.sessionStorage.getItem('token')
  if(token === null || token === ''){
     return next("/login")
  }
  //放行请求
  next()
})

export default router